// 购物车模块
import { defineStore } from 'pinia'
import { ref, computed, watch, onMounted } from 'vue'

export const useShopCart = defineStore('shopCart', () => {
  const cartList = ref([])
  watch(
    cartList,
    (newValue) => {
      localStorage.setItem('cartList', JSON.stringify(newValue))
    },
    { deep: true }
  )
  const addCart = (goods) => {
    // 添加购物车数据
    // 以添加count++
    // 没有push,添加
    const item = cartList.value.find((item) => item.skuId === goods.skuId)
    if (item) {
      item.count += goods.count
    } else {
      cartList.value.push(goods)
    }
  }
  const delCart = (skuId) => {
    const index = cartList.value.findIndex((item) => item.skuId === skuId)
    if (index !== -1) {
      cartList.value.splice(index, 1)
    }
    localStorage.setItem('cartList', JSON.stringify(cartList.value))
  }
  const clearCart = () => {
    cartList.value = []
    // 同时清除本地存储
    localStorage.removeItem('cartList')
  }

  const clearcheckoutCart = () => {
    const unCheckCArtList = ref()
    unCheckCArtList.value = cartList.value.filter((item) => item.select === false)
    cartList.value = unCheckCArtList.value
  }
  const total = computed(() => {
    return cartList.value.reduce((sum, item) => sum + item.count, 0)
  })
  // c
  const totalPrice = computed(() => {
    return cartList.value.reduce((sum, item) => {
      return sum + Number(item.count) * Number(item.price)
    }, 0)
  })
  //购物车所有选中商品的价格
  const totalCheckPrice = computed(() => {
    return cartList.value.reduce((sum, item) => {
      if (item.select) {
        return sum + Number(item.count) * Number(item.price)
      }
      return sum
    }, 0)
  })

  const totalCheck = computed(() => {
    const checkCArtList = ref()
    checkCArtList.value = cartList.value.filter((item) => item.select === true)
    return checkCArtList.value.reduce((sum, item) => sum + item.count, 0)
  })

  onMounted(() => {
    const storedCart = localStorage.getItem('cartList')
    if (storedCart) {
      cartList.value = JSON.parse(storedCart)
    }
  })
  return {
    total,
    totalPrice,
    totalCheckPrice,
    totalCheck,
    cartList,
    addCart,
    delCart,
    clearCart,
    clearcheckoutCart
  }
})
